package com.macro.mall.controller.advice;

import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 使用 Spring 的织入。
 * <p> {@link AdviceController#exceptionHandler(Exception)} 获取异常信息进行统一处理。
 */
@RestControllerAdvice
@Slf4j
public class AdviceController {

    /**
     * 获取信息进行统一处理
     *
     * @param ex 异常
     * @return {@link CommonResult}
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = Exception.class)
    public CommonResult exceptionHandler(Exception ex) {
        if (ex instanceof BusinessException) {
            log.info("请稍后再试: {}", ex.getMessage());
            return CommonResult.failed("请稍后再试: " + ex.getMessage());
        } else if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException e = (MethodArgumentNotValidException) ex;
            String errorMessage = e.getBindingResult().getFieldError().getDefaultMessage();
            log.info("校验错误: {}", errorMessage);
            return CommonResult.failed("校验错误:" + errorMessage);
        }
        return CommonResult.failed();
    }

}
